// ==UserScript==
// @name         视频控制
// @description  视频控制，添加部分快捷键。b站弹幕开关接管，提升开关效率。b站中键进入全屏

// @namespace    https://gitee.com/anhaku/video-control
// @version      0.7.6


// @author       Anhaku
// @license      MIT

// @match        *://*/*
// @grant        none
// @run-at       document-end

// @updateURL    https://gitee.com/anhaku/video-control/raw/master/video_control.js
// @downloadURL  https://gitee.com/anhaku/video-control/raw/master/video_control.js
// ==/UserScript==
! function () {
    function $($ = "") {
        return document.querySelector($);
    }

    function getPlayer() { //寻找最长的视频，没有返回false
        if (window.longestPlayer) {
            return window.longestPlayer;
        }

        function objToArr(obj) { //节点集合转换为数组
            let arr = [];
            for (let index = 0; index < obj.length; index++) {
                arr.push(obj[index]);
            }
            return arr
        }

        function arrPush(arr, arr2) { //拼接数组
            for (let index = 0; index < arr2.length; index++) {
                arr.push(arr2[index]);
            }
            return arr
        }

        function scheduleVideo() { //寻找所有video
            let videoArr = objToArr(document.querySelectorAll('video'));
            let videoBiliArr = objToArr(document.querySelectorAll('bwp-video'));
            return arrPush(videoArr, videoBiliArr);
        }
        let players = scheduleVideo();
        if (!players || !players.length) return false
        let time = 0;
        let longestPlayer = false;
        for (let index = 0; index < players.length; index++) {
            const element = players[index];
            if (element.duration > time) {
                longestPlayer = element;
                time = element.duration;
            }
        }
        window.longestPlayer = longestPlayer
        return longestPlayer
    }

    function CreateVolumeHint() { //创建音量提示牌
        let volumeHint = document.createElement('div');
        volumeHint.className = 'volumeHint';
        volumeHint.style.display = 'none';
        volumeHint.style.position = 'absolute';
        volumeHint.style.top = "50%";
        volumeHint.style.left = "50%";
        volumeHint.style.width = "60px";
        volumeHint.style.height = "32px";
        volumeHint.style.zIndex = '10000';
        volumeHint.style.fontSize = '20px';
        volumeHint.style.marginLeft = '-40px';
        volumeHint.style.marginTop = '-25px';
        volumeHint.style.background = 'hsla(0,0%,100%,.8)';
        volumeHint.style.borderRadius = '4px';
        volumeHint.style.lineHeight = '32px';
        volumeHint.style.textAlign = 'center';
        getPlayer().parentElement.appendChild(volumeHint);
        return volumeHint;
    }

    var VolumeTimeOut;

    function showVolumeHint(volume) { //显示音量
        let volumeHint = $(".volumeHint");
        volumeHint.innerText = volume + "%";
        volumeHint.style.display = 'block';
        VolumeTimeOut && clearTimeout(VolumeTimeOut);
        VolumeTimeOut = setTimeout(() => {
            volumeHint.style.display = 'none';
        }, 1000);
    }

    function changeVolume(up) { //更改音量大小
        var player = getPlayer();
        let volume = player.volume;
        volume = Math.round(volume * 100);
        if (up) {
            if (volume >= 90) {
                volume = 100;
            } else if (volume < 10) {
                volume += 1;
            } else if (volume < 20) {
                volume += 5;
            } else {
                volume += 10;
            }
        } else {
            if (volume <= 1) {
                volume = 0;
            } else if (volume <= 10) {
                volume -= 1;
            } else if (volume <= 20) {
                volume -= 5;
            } else {
                volume -= 10;
            }
        }
        player.volume = volume / 100;
        showVolumeHint(volume)
    }
    document.addEventListener('keydown', function (e) { //绑定按键事件
        var player = getPlayer();
        let volumeHint = $(".volumeHint");
        volumeHint ? volumeHint = volumeHint[0] : volumeHint = CreateVolumeHint();
        switch (e.key) {
            case "q": //快退
                player.currentTime -= 80;
                break;
            case "e":
            case '0':
            case 'Insert': //快进
                window.location.host == 'www.bilibili.com' && player.currentTime + 85 > player.duration ? $('.squirtle-video-next').click() : player.currentTime += 85;
                break;
            case "w":
                changeVolume(true);
                break;
            case "s":
                changeVolume(false);
                break;
            case "a":
                player.currentTime -= 5;
                break;
            case "d":
                player.currentTime += 5;
                break;
            case "ArrowDown":
            case "ArrowUp":
                if (window.location.host != 'www.bilibili.com')
                    setTimeout(() => {
                        showVolumeHint(Math.round(player.volume * 100));
                    }, 100);
                break;
        }
    });
    //===========================================bilibili相关=====================================================================
    if (window.location.href.search(/www.bilibili.com\/((video)|(bangumi))/) == -1) return
    let danmaku_switchInput_className = "bui-area";
    let danmaku_wrap_className = "bpx-player-row-dm-wrap";
    let videoWrap_className = "bpx-player-video-wrap";
    let fullScreenBtn_className = "squirtle-video-fullscreen";
    if (window.location.href.search(/www.bilibili.com\/video/) != -1) {
        danmaku_switchInput_className = "bilibili-player-video-danmaku-switch";
        danmaku_wrap_className = "bilibili-player-video-danmaku";
        videoWrap_className = "player-wrap";
        fullScreenBtn_className = "bilibili-player-iconfont-fullscreen-off";
    }


    function replace() { //接管弹幕控制按钮
        let danmakuSwitch = $('.' + danmaku_switchInput_className);
        let danmakuRoot = danmakuSwitch.parentElement;
        let Clone = danmakuSwitch.cloneNode(true)
        Clone.className += ' danmakuSwitchClone'
        Clone.querySelector('input').addEventListener('change', danmakuChange)
        //替换按钮
        danmakuRoot.removeChild(danmakuSwitch)
        danmakuRoot.insertBefore(Clone, danmakuRoot.children[0])
        if (!$('.bui-switch-input').checked) {
            $('.' + danmaku_wrap_className).style.visibility == 'hidden'
            $('.bui-switch-input').click();
        }
        document.removeEventListener('click', display)
    }

    function display(e) { //替换
        if (e.target.className == danmaku_switchInput_className) setTimeout(replace, 50);
    }
    document.addEventListener('click', display)

    function danmakuChange() { //开关弹幕
        let danmaku = $('.' + danmaku_wrap_className);
        let buiSwitchInput = $('.' + danmaku_switchInput_className);
        buiSwitchInput = buiSwitchInput.querySelector('input');
        if (danmaku.style.visibility == 'hidden') {
            danmaku.style.visibility = '';
            buiSwitchInput.checked = true;
        } else {
            danmaku.style.visibility = 'hidden';
            buiSwitchInput.checked = false;
        }
    }
    document.addEventListener('keyup', function (e) { //弹幕快捷键
        if (e.key == '`') {
            if (!$('.danmakuSwitchClone')) replace();
            danmakuChange();
        }
    })
    ///全屏工具
    function find_appoint_parent(parent_classname, element) { //递归寻找特定父节点
        if (element.parentElement.className.search(parent_classname) == -1) { //没有找到目标父节点
            if (element.parentElement.nodeName == "HTML") { //位于文档根部
                return false;
            } else {
                return find_appoint_parent(parent_classname, element.parentElement);
            }
        } else { //找到目标父节点
            return true;
        }
    }

    document.addEventListener('dblclick', function (e) { ///双击全屏
        if (!find_appoint_parent(videoWrap_className, e.target)) return;
        $('.' + fullScreenBtn_className).click();
        $('.bpx-player-ctrl-btn').click();
    })

    document.onmousedown = function (e) { ///中键全屏
        if (!(e.button == 1 && find_appoint_parent(videoWrap_className, e.target))) return;
        if (e.button == 1) {
            if (!document.webkitIsFullScreen) {
                getPlayer().play(); //鼠标中键播放
            }
            $('.' + fullScreenBtn_className).click();
            $('.bpx-player-ctrl-btn').click();
            return false;
        }
    }
    console.log('已载入控制脚本');
}();
